<template>
  <div id="org-manager">
    <v-header title="机构管理" :showDownloadBtn="false" :saveShow="false"></v-header>
    <!--主页面内容-->
    <div class="box">
      <el-header height="58px">
        <el-row class="toolbar">
          <el-button type="primary" size="mini" @click="addOrgBtnClick">增加</el-button>
          <el-button type="primary" size="mini" @click="delOrgBtnClick">删除</el-button>
          <el-button type="primary" size="mini" @click="editOrgBtnClick">编辑</el-button>
          <el-button type="primary" size="mini" @click="refreshOrgTreeData">刷新</el-button>
        </el-row>
      </el-header>
      <el-main style="margin-bottom: 20px">
        <org-tree-grid ref="orgTreeGrid"></org-tree-grid>
      </el-main>
    </div>

    <!--下面放弹出的内容-->
    <template>
      <!--参照DdataBoard.vue中的新增看板-->
      <el-dialog
        :title="addOrgDialogMode == 'ADD' ? '新增机构' : '编辑机构'"
        :visible.sync="addOrgDialogVisiable"
        v-model="addOrgDialogMode"
        @close="ardCancelBtnClick"
        width="822px">
        <el-form
                 ref="addForm"
                 :model="addFormData"
                 :rules="addOrgRules"
                 label-width="120px"
                 :label-position="'right'">
          <el-row :gutter="24" v-if="addOrgDialogMode === 'ADD'">
            <el-col :span="12">
              <el-form-item label="新增一级机构" prop="isRoot">
                <el-switch v-model="addFormData.isRoot"
                  active-value="on"
                  inactive-value="off"
                  :disabled="addFormData.isRootSwitchAbled"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
                <span class="ml5">{{addFormData.isRoot === 'on' ? '是' : '否'}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上级机构" prop="uper" v-show="addFormData.isRoot === 'off'">
                <!-- 上级机构名称 -->
                <el-input v-model="addFormData.pname"
                          placeholder="请在此输入"
                          disabled>
                </el-input>
                <!-- 上级机构id，隐藏的 -->
                <el-input v-model="addFormData.parentId"
                          v-show="false"
                          :contenteditable="false">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="机构号" prop="id">
                <el-input v-model="addFormData.id"
                           placeholder="请在此输入">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机构名称" prop="name">
                <el-input v-model="addFormData.name"
                          placeholder="请在此输入">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="属地" prop="locid">
                <!--<el-input v-model="addFormData.locid"-->
                          <!--placeholder="请在此输入">-->
                <!--</el-input>-->
                <locs-cascader v-model="addFormData.locid" ref="child"></locs-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label=" 是否启用" prop="isValid">
                <el-switch v-model="addFormData.isValid"
                  active-color="#13ce66"
                  active-value="Y"
                  inactive-value="N"
                  inactive-color="#ff4949">
                </el-switch>
                <span class="ml5">{{addFormData.isValid === 'Y' ? '启用' : '禁用'}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <!-- 提交的时候拆出开始时间beginDt和结束时间endDt -->
              <el-form-item label="有效日期" prop="availDate">
                <el-date-picker v-model="addFormData.availDate"
                                type="daterange"
                                align="right"
                                unlink-panels
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="resetForm('addForm')" class="dialog-btn">重置</el-button>
            <el-button @click="ardCancelBtnClick" class="dialog-btn">关闭</el-button>
            <el-button @click="submitFormData" type="primary" class="dialog-btn">确定</el-button>
        </span>
      </el-dialog>
    </template>
  </div>
</template>

<script type="text/ecmascript-6">
  import {VHeader} from '../../../components'
  import OrgTreeGrid from './orgTreeGrid'
  import ajax from '../../../api/ajax'
  import Msg from '../../../assets/js/msg'
  import api from '../../../api/url'
  import {notCnValidator} from '../../../assets/js/rules'
  import {formatDate} from 'element-ui/packages/date-picker/src/util'
  import LocsCascader from './locsCascader'

  export default {
    name: 'org-manager',
    data () {
      return {
        addOrgDialogVisiable: false, // 新增角色对话框显示控制
        addOrgDialogMode: { // 对话框色对话框模式  ADD新增 MODIFY 修改
          type: String,
          default: 'ADD'
        },
        currentItem: {
          // isRootSwitchAbled 在不选择记录的时候，是否是新增一级菜单应该是不可用的。这里默认为可用
          isRootSwitchAbled: false, // true 禁用
          isRoot: 'on', // 是否是新增顶级机构
          isValid: 'Y' // 是否启用
        },
        addFormData: {}, // 新增角色对话框表单数据
        addOrgRules: {
          id: [ // 机构号
            { required: true, message: '请输入机构号', trigger: 'blur' },
            { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
            { validator: notCnValidator, trigger: 'blur' }
          ],
          name: [ // 机构名称
            { required: true, message: '请输入机构名称', trigger: 'blur' },
            { min: 1, max: 60, message: '长度在 1 到 60 个字符', trigger: 'blur' }
          ],
          locid: [ // 选择属地
            { required: true, message: '请选择属地', trigger: 'blur' }
          ],
          availDate: [ // 有效日期
            { required: true, message: '请选择有效日期', trigger: 'blur' }
          ]
        }
      }
    },
    components: {
      LocsCascader,
      OrgTreeGrid,
      VHeader
    },
    methods: {
      // 新增机构按钮
      addOrgBtnClick () {
        // 显示新增机构对话框
        this.addOrgDialogVisiable = true
        // 新增机构对话框模式
        this.addOrgDialogMode = 'ADD'
        // 获取选择的数据
        let currentNode = this.$refs.orgTreeGrid.getCurrentNode()
        if (currentNode) {
          /*
            如果当前选中了一条数据，那么要将选择的数据的相关值初始化到新增表单中去
          */
          // 做数据适配处理
          let currentNodeCopy = JSON.parse(JSON.stringify(currentNode))
          this.currentItem = {
            isRootSwitchAbled: false, // 打开能切换是否是新增一级菜单
            isRoot: 'off', // 是否是新增一级机构
            layer: currentNodeCopy['layer'],
            parentId: currentNodeCopy['id'], // 上级机构id
            pname: currentNodeCopy['name'], // 上级机构名称
            isValid: 'Y' // 是否启用
          }
          this.addFormData = {...this.currentItem}
        }
      },
      // 删除机构按钮
      delOrgBtnClick () {
        // 获取选择的数据
        let currentNode = this.$refs.orgTreeGrid.getCurrentNode()
        if (!currentNode) {
          this.$message.error('请选择一条要删除的记录')
        } else {
          // 确定删除选中的机构信息吗？
          Msg.confirm(`确定删除机构名称为【${currentNode.name}】的机构吗？`, {
            onConfirm: () => {
              let postData = currentNode
              ajax.post(api.DEL_SYS_ORG, postData).then(res => {
                // 刷新数据
                this.refreshOrgTreeData()
                // 取消删除的选择
                this.$refs.orgTreeGrid.cancelCurrentSelect()
              })
            },
            onCancel () {
            }
          })
        }
      },
      // 编辑机构按钮
      editOrgBtnClick () {
        // 获取选择的数据
        let currentNode = this.$refs.orgTreeGrid.getCurrentNode()
        if (!currentNode) {
          this.$message.error('请选择一条要编辑的数据')
        } else {
          // 显示编辑机构对话框
          this.addOrgDialogVisiable = true
          // 新增机构对话框模式
          this.addOrgDialogMode = 'MODIFY'

          let currentNodeCopy = JSON.parse(JSON.stringify(currentNode))
          // 开始日期和结束日期这里要特殊处理下，表单中就一个有效期（包含了开始和结束）
          currentNodeCopy['availDate'] = [
            formatDate(currentNodeCopy['beginDt']),
            formatDate(currentNodeCopy['endDt'])
          ]
          delete currentNodeCopy['beginDt']
          delete currentNodeCopy['endDt']
          // 数组
          currentNodeCopy['locid'] = [currentNodeCopy['locid']]
          if (currentNodeCopy['children']) {
            delete currentNodeCopy['children']
          }
          this.currentItem = currentNodeCopy
          this.addFormData = {...this.currentItem}
        }
      },
      // 取消新增
      ardCancelBtnClick () {
        this.addOrgDialogVisiable = false
        // 清空数据
        // this.addFormData = {}
        this.addFormData = {...this.currentItem}
        // 清除验证
        this.$refs.addForm.clearValidate()
        // 清空联级选择器
        this.$refs.child.clearCascader()
      },
      // 预处理表单数据
      preHandFormData (formData) {
        let isRoot = formData['isRoot']
        let availDate = formData['availDate']
        let parentId = formData['parentId']
        let pname = formData['pname']
        let locids = formData['locid']
        let locid = locids[locids.length - 1]

        // 如果是新增一级机构，需要将上级机构和上级机构名称清空
        if (isRoot === 'on') {
          parentId = null
          pname = null
        }

        return {
          isRoot,
          id: formData['id'],
          isValid: formData['isValid'],
          layer: formData['layer'],
          locid: locid,
          name: formData['name'],
          beginDt: availDate[0],
          endDt: availDate[1],
          parentId,
          pname
        }
      },
      // 刷新机构树数据
      refreshOrgTreeData () {
        this.$refs.orgTreeGrid.getAllOrgTreeData()
      },
      // 新增机构
      addOrg (postData, callback) {
        ajax.post(api.ADD_SYS_ORG, postData).then(res => {
          callback && callback()
        })
      },
      // 修改机构
      updateOrg (postData, callback) {
        ajax.post(api.MODIFY_SYS_ORG, postData).then(res => {
          callback && callback()
        })
      },
      // 提交新增机构数据
      submitFormData () {
        // console.info(this.addFormData)
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            let postData = this.preHandFormData(this.addFormData)
            let callback = () => {
              // 刷新数据
              this.refreshOrgTreeData()
              // 隐藏新增对话框
              this.addOrgDialogVisiable = false
              // 数据清空
              setTimeout(() => {
                this.resetForm('addForm')
              }, 200)
            }
            if (this.addOrgDialogMode === 'ADD') {
              this.addOrg(postData, callback)
            } else if (this.addOrgDialogMode === 'MODIFY') {
              this.updateOrg(postData, callback)
            }
          } else {
            return false
          }
        })
      },
      // 重置表单
      resetForm (formName) {
        this.addFormData = {...this.currentItem}
        // 清空联级选择器
        this.$refs.child.clearCascader()
        // 清除验证
        this.$refs[formName].clearValidate()
      }
    },
    created () {
      // 默认表单数据初始化
      this.addFormData = JSON.parse(JSON.stringify(this.currentItem))
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
#org-manager
  font-size 14px
  .box
    height calc(100% - 56px)
    padding 10px
  .el-header
    padding 0 0
    margin-bottom 3px
    .toolbar
      height 50px
      line-height 50px
      vertical-align middle
      background-color #fff
      padding 2px 15px
  .el-main
    padding 0 0
  .el-dialog
    .el-form
      .el-date-editor.el-range-editor
        width: 260px !important
        height 40px
</style>
